﻿namespace PlanckSys.Jira.RssJiraRedirector
{
    #region Imports
    using System.Net.Http;
    using ConfigurationManager = System.Configuration.ConfigurationManager;
    using Exception = System.Exception;
    using MediaTypeHeaderValue = System.Net.Http.Headers.MediaTypeHeaderValue;
    using HttpResponseMessage = System.Net.Http.HttpResponseMessage;
    using StringContent = System.Net.Http.StringContent;
    using HttpStatusCode = System.Net.HttpStatusCode;
    #endregion

    public class RssJiraRedirectApiController : System.Web.Http.ApiController
    {


        // GET api/<controller>
        public HttpResponseMessage Get(string jiraUrl)
        {/// http://localhost:820/RssJiraRedirectApi/jiraUrl/?jiraUrl=http://pmodbp:8080/sr/jira.issueviews:searchrequest-rss/54848/SearchRequest-54848.xml?tempMax=10
            try
            {


                string jiraBaseURL = ConfigurationManager.AppSettings["JiraBaseURL"];
                string jiraUser = ConfigurationManager.AppSettings["JiraUser"];
                string jiraPass = ConfigurationManager.AppSettings["JiraPass"];
                string jiraProxyHost = ConfigurationManager.AppSettings["JiraProxyHost"];
                string jiraProxyUser = ConfigurationManager.AppSettings["JiraProxyUser"];
                string jiraProxyPass = ConfigurationManager.AppSettings["JiraProxyPass"];
                string jiraVersion = ConfigurationManager.AppSettings["JiraVersion"];



                NoRedirectCookieAwareWebClient httpclient = new NoRedirectCookieAwareWebClient();

                RssJiraRedirector.JiraDao jd = new RssJiraRedirector.JiraDao(jiraBaseURL);
                jd.AuthProxy(httpclient, jiraProxyHost, jiraProxyUser, jiraProxyPass);
                jd.DoLogin(httpclient, jiraUser, jiraPass);
                string rss = jd.ProxeyUrl(httpclient, jiraUrl);

                HttpResponseMessage resp = Request.CreateResponse(HttpStatusCode.OK);
                resp.Content = new StringContent(rss);
                resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/rss+xml");

                return resp;

            }
            catch (Exception e)
            {
                //wrap up all exceptions to be user friendly
                if (RssJiraRedirectorService.eventLog1 != null)
                {
                    if (e is RssJiraRedirector.JiraDaoException)
                    {
                        e = e.InnerException;
                    }
                    string message = string.Format("error {0}, Exception: {1} \n\nStack: {2}\n\njiraUrl: {3}", "Log", e.Message, e.StackTrace, jiraUrl);
                    RssJiraRedirectorService.eventLog1.WriteEntry(message, System.Diagnostics.EventLogEntryType.Error);
                }
                throw;
            }
        }
    }
}
